﻿CREATE PROCEDURE [Event].[CreateNewLocation]
  @Title NVARCHAR(255),
	@Address1 NVARCHAR(255) = NULL,
	@Address2 NVARCHAR(255) = NULL,
	@City NVARCHAR(50) = NULL,
	@State NVARCHAR(50) = NULL,
	@PostalCode NVARCHAR(10) = NULL,
	@Directions NVARCHAR(2000) = NULL,
	@LocationID INT OUTPUT,
	@Coordinates GEOGRAPHY = NULL
WITH EXECUTE AS OWNER
AS
SET NOCOUNT ON;
BEGIN TRY
  BEGIN TRANSACTION;
  
  INSERT INTO [Event].[Locations]
  (
    Address1,
    Address2,
    City,
    State,
    PostalCode,
    Directions,
    Coordinates
  )
  VALUES
  (
    @Address1,
    @Address2,
    @City,
    @State,
    @PostalCode,
    @Directions,
    @Coordinates
  );
  
  SET @LocationID = SCOPE_IDENTITY();
  
  COMMIT TRANSACTION;
END TRY
BEGIN CATCH
  SET @LocationID = -1;
  
  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
  
  DECLARE @ERROR_SEVERITY AS INT,
          @ERROR_STATE AS INT,
          @ERROR_NUMBER AS INT,
          @ERROR_LINE AS INT,
          @ERROR_MESSAGE AS NVARCHAR(4000);

  SELECT @ERROR_SEVERITY = ERROR_SEVERITY(),
         @ERROR_STATE = ERROR_STATE(),
         @ERROR_NUMBER = ERROR_NUMBER(),
         @ERROR_LINE = ERROR_LINE(),
         @ERROR_MESSAGE = ERROR_MESSAGE();

  RAISERROR('Msg %d, Line %d, :%s',
            @ERROR_SEVERITY,
            @ERROR_STATE,
            @ERROR_NUMBER,
            @ERROR_LINE,
            @ERROR_MESSAGE);
END CATCH